<template>
	<view class="calendar-container">
		<!-- 头部年月选择器 -->
		<view class="calendar-header">
			<view class="calendar-icon"></view>
			<picker mode="date" :value="formattedCurrentDate" @change="onDateChange" fields="month">
				<view class="title">
					<view>{{ currentYear }} {{ currentMonth }}月</view>
					<image src="@/img/yangcan/ic_color_xia.png"></image>
				</view>
			</picker>
			<image class="calendar-icon" src="@/img/yangcan/rili.png"></image>
		</view>
		<!-- 星期标题 -->
		<slot>
			<view class="calendar-week">
				<view class="week-item">日</view>
				<view class="week-item">一</view>
				<view class="week-item">二</view>
				<view class="week-item">三</view>
				<view class="week-item">四</view>
				<view class="week-item">五</view>
				<view class="week-item">六</view>
			</view>
		</slot>
		<!-- 内容 -->
		<view class="expand-wrapper" :style="{height: isExpand ? 'calc(100% - 226rpx)' : '90rpx' }">
			<scroll-view scroll-y style="height: calc(100% - 90rpx);">
			<view class="calendar-body">
				<view class="calendar-row" v-for="(row, rowIndex) in calendarData" :key="rowIndex">
					<view class="calendar-day" v-for="(day, colIndex) in row" :key="colIndex" :class="{
							'prev-month': day.type === 'prev',
							'next-month': day.type === 'next',
							'current-month': day.type === 'current',
							'today': isToday(day.date),
							'calendar-day-selected': getEventsByDate(day.date).length > 0 && day.type === 'current', 
						}" @click="selectDate(day.date)">
						<view class="day-number">{{ day.day }}</view>
						<view v-if="getEventsByDate(day.date).length > 0 && day.type === 'current'" class="event-list">
							<view class="event-item" :style="{backgroundColor: event.isExpire ? '#a9a9a9' : '#fe8520'}"  v-for="(event, eventIndex) in getEventsByDate(day.date)"
								:key="eventIndex">
								{{ event.name }}
							</view>
						</view>
						<!-- <view v-if="getEventsByDate(day.date).length > 0" class="day-mark"></view> -->
					</view>
				</view>
			</view>
			</scroll-view>

			<view class="expand-arrow">
				<image class="arrow-icon" :class="{'arrow-icon-selected': isExpand}" src="@/img/yangcan/xia.png"
					@click="onExpand" />
			</view>
		</view>
	</view>
</template>

<script>
	import StorageUtils from '@/utils/StorageUtils.js';
	import CacheConfig from '@/config/CacheConfig.js';
	import * as ReservationApi from '@/api/reservation/index.js';
	
	export default {
		name: 'calendar',
		props: {
			// 选中日期
			selectedDate: {
				type: String,
				default: ''
			},
		},
		data() {
			return {
				currentDate: new Date(),
				currentYear: 0,
				currentMonth: 0,
				currentPage: 1, // 0:上个月, 1:当月, 2:下个月

				calendarData: [],
				prevMonthData: [],
				nextMonthData: [],
				
				eventList: [],

				isExpand: false,
			}
		},
		mounted() {
			// uni.createSelectorQuery().in(this).select('.calendar-scroll').boundingClientRect((rect) => {
			// 	console.log("rect.width", rect.width)
			// 	this.pageWidth = rect.width;
			// }).exec();
		},
		computed: {
			formattedSelectedDate() {
				return this.formatDate(this.selectedDate);
			},
			formattedCurrentDate() {
				const year = this.currentDate.getFullYear();
				const month = this.currentDate.getMonth();
				return `${year}-${month + 1}`;
			}
		},
		watch: {
			// 监听选中日期变化
			selectedDate: {
				handler(newVal) {
					this.generateCalendar();
				},
				immediate: true
			},
		},
		mounted() {
			// this.initData();
			this.initCalendar();
		},
		methods: {
			initData() {
				const year = this.currentDate.getFullYear();
				const month = this.currentDate.getMonth() + 1;
				const firstDay = new Date(year, month - 1, 1, 0, 0, 0);
				const lastDay = new Date(year, month, 0, 23, 59, 59);
				const formatDateTime = (date) => {
					const year = date.getFullYear();
					const month = String(date.getMonth() + 1).padStart(2, '0');
					const day = String(date.getDate()).padStart(2, '0');
					const hours = String(date.getHours()).padStart(2, '0');
					const minutes = String(date.getMinutes()).padStart(2, '0');
					const seconds = String(date.getSeconds()).padStart(2, '0');
					return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
				};
				const start = formatDateTime(firstDay);
				const end = formatDateTime(lastDay);
				console.log("firstDay", start);
				console.log("lastDay", end);
				const userInfo = StorageUtils.get(CacheConfig.USER_INFO_KEY);
				const param = {
					current: 1,
					size: 1000000,
					userId: userInfo.id,
					searchStart: start,
					searchEnd: end,
				};
				ReservationApi.getReservationPage(param).then(res => {
					if (!!res.obj) {
						const list = res.obj.records.map(v => {
							const name = v.reserveItemVo?.itemName || "未知";
							const startDate = new Date(v.startTime);
							return {
								...v,
								title: `${name}体验预约`,
								time: `${v.startTime}`,
								timeRange: `${v.startTime}-${this.$u.timeFormat(v.endTime, 'hh:MM:ss')}`,
								isExpire: Date.now() > startDate.getTime(),
								name,
							}
						})
						this.eventList = list;
					}
				})
			},
			// 初始化日历
			initCalendar() {
				this.currentYear = this.currentDate.getFullYear();
				this.currentMonth = this.currentDate.getMonth() + 1;
				this.generateCalendar();
			},
			// 生成日历数据
			generateCalendar() {
				const firstDay = new Date(this.currentYear, this.currentMonth - 1, 1);
				const lastDay = new Date(this.currentYear, this.currentMonth, 0);
				// 获取当月第一天是星期几(0-6)
				const firstDayWeekday = firstDay.getDay();
				// 获取上个月的最后几天
				const prevMonthLastDay = new Date(this.currentYear, this.currentMonth - 1, 0).getDate();
				// 生成日历数据
				let calendar = [];
				let dayCount = 1;
				let nextDayCount = 1;
				// 计算需要生成的行数
				const totalDays = firstDayWeekday + lastDay.getDate();
				const rows = Math.ceil(totalDays / 7);
				for (let i = 0; i < rows; i++) {
					let week = [];
					for (let j = 0; j < 7; j++) {
						let dateObj = {};
						if (i === 0 && j < firstDayWeekday) {
							// 上个月的日期
							const day = prevMonthLastDay - (firstDayWeekday - j - 1);
							const date = new Date(this.currentYear, this.currentMonth - 2, day);
							dateObj = {
								day,
								type: 'prev',
								date: this.formatDate(date)
							};
						} else if (dayCount <= lastDay.getDate()) {
							// 当月的日期
							const date = new Date(this.currentYear, this.currentMonth - 1, dayCount);
							dateObj = {
								day: dayCount,
								type: 'current',
								date: this.formatDate(date),
								// mark: this.markedDates.includes(this.formatDate(date))
							};
							dayCount++;
						} else {
							// 下个月的日期
							const date = new Date(this.currentYear, this.currentMonth, nextDayCount);
							dateObj = {
								day: nextDayCount,
								type: 'next',
								date: this.formatDate(date)
							};
							nextDayCount++;
						}
						week.push(dateObj);
					}
					calendar.push(week);
				}
				this.calendarData = calendar;
			},
			// 格式化日期为 YYYY-MM-DD
			formatDate(date) {
				if (!date) return '';
				if (typeof date === 'string') {
					// 处理字符串格式的日期
					if (date.split(' ').length > 1) {
						return date.split(' ')[0]; // 直接截取日期部分
					}
					if (date.split('-').length === 3) return date;
					date = new Date(date);
				}
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				return `${year}-${month}-${day}`;
			},
			// 根据日期获取事件
			getEventsByDate(date) {
				return this.eventList.filter(event => {
					const realTime = this.formatDate(event.time);
					if (this.formatDate(event.time) === date) {
						return true;
					}
				});
			},
			// 上个月
			prevMonth() {
				this.currentMonth--;
				if (this.currentMonth < 1) {
					this.currentMonth = 12;
					this.currentYear--;
				}
				this.generateCalendar();
			},
			// 下个月
			nextMonth() {
				this.currentMonth++;
				if (this.currentMonth > 12) {
					this.currentMonth = 1;
					this.currentYear++;
				}
				this.generateCalendar();
			},
			// 选择日期
			selectDate(date) {
				// 如果选择的是当月日期
				if (date.split('-')[1] === String(this.currentMonth).padStart(2, '0')) {
					this.$emit('dateChange', date);
				}
			},
			// 判断是否是今天
			isToday(date) {
				const today = this.formatDate(new Date());
				return today === date;
			},
			onExpand() {
				this.isExpand = !this.isExpand;
			},
			onDateChange(e) {
				console.log("onDateChange e", e);
				this.currentDate = new Date(e.detail.value);
				this.initData();
				this.initCalendar();
				this.selectDate(`${e.detail.value}-01`);
			}
		}
	}
</script>

<style lang="scss" scoped>
	.calendar-container {
		background-color: #fff;

		.calendar-header {
			width: 100%;
			height: 80rpx;
			display: flex;
			text-align: center;
			justify-content: space-between;
			padding: 0 10rpx;
			font-weight: bold;
			color: #f08800;

			.calendar-icon {
				width: 40rpx;
				height: 40rpx;
				margin-top: 20rpx;
			}

			.title {
				height: 80rpx;
				display: flex;
				align-items: center;

				image {
					width: 40rpx;
					height: 40rpx;
					margin-left: 19rpx;
				}
			}
		}

		.calendar-week {
			display: flex;
			padding: 20rpx 0;
			border-bottom: 1rpx solid #ccc;

			.week-item {
				flex: 1;
				text-align: center;
				font-size: 28rpx;
				color: #666;
			}
		}

		.calendar-wrapper {
			width: 100%;
			overflow: hidden;
		}

		.calendar-scroll {
			white-space: nowrap;
			width: 300%;
			box-sizing: content-box;
		}

		.calendar-pages {
			display: flex;
			width: 300%;
			transition: transform 0.3s ease;

			.calendar-page {
				display: inline-block;
				width: 33.333%;
				box-sizing: content-box;
				padding: 0 20rpx;
			}
		}

		.expand-wrapper {
			position: absolute;
			left: 0;
			// top: 226rpx;
			width: 100%;
			background-color: #fff;
			overflow: hidden;
			z-index: 9;
			transition: height 0.2s ease;

			.expand-arrow {
				width: 100%;
				padding: 20rpx;
				background-color: #fff;
				position: absolute;
				bottom: 0;
				left: 0;

				.arrow-icon {
					width: 46rpx;
					height: 46rpx;
					margin: 0 auto;
					display: block;
				}

				.arrow-icon-selected {
					width: 46rpx;
					height: 46rpx;
					margin: 0 auto;
					display: block;
					transform: rotate(180deg);
				}
			}
		}

		.calendar-body {
			display: flex;
			flex-direction: column;

			.calendar-row {
				display: flex;
				border-bottom: 1rpx solid #ccc;
				padding: 5rpx 0;

				.calendar-day {
					flex: 1;
					min-height: 200rpx;
					margin: 0 5rpx;
					border-radius: 20rpx;
					display: flex;
					flex-direction: column;
					align-items: center;
					cursor: pointer;
					position: relative;
				}

				.calendar-day-selected {
					background-color: #fef5ed;
					font-weight: bold;
				}
			}
		}
	}

	.event-list {
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-top: 20rpx;

		.event-item {
			font-size: 20rpx;
			font-weight: 400;
			color: #fff;
			padding: 5rpx 8rpx;
			background-color: #ff7e35;
			border-radius: 10rpx;
			margin-bottom: 10rpx;
		}
	}

	.prev-month,
	.next-month {
		color: #ccc;
	}

	.current-month {
		color: #333;
	}

	.today {
		font-weight: bold;
	}

	.day-number {
		font-size: 14px;
		margin-top: 10rpx;
	}

	.day-mark {
		width: 4px;
		height: 4px;
		background-color: #f56c6c;
		border-radius: 50%;
		position: absolute;
		bottom: 5px;
	}
</style>